﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eTerm.MsSql.DbProvider;
using eTerm.ASynClientSDK;
using System.Text.RegularExpressions;
using eTerm.NetSocket.Utils;

namespace eTerm.Platform.Web.Order.UserControls
{
    public partial class PNRMode : BaseEntityUserControl<PnrRequire>
    {
        protected override void SaveEntity(PnrRequire model)
        {

            model.Save();

            //分析PNR原始信息
            PNRInfo PnrInfoResult = new AnalysisPRN(model.PnrCode, model.Description).ParsePNR();
            PnrInfoResult.SegmentList.ToList().ForEach(l => {
                new PnrSegment() { 
                     Arrival = l.ArrivalAirport,
                      CabinCode = l.Carbin , 
                       Departure = l.DepartureAirport,
                     RequireId = model.Id,
                        DepartureDate = getDateString(l.Date),
                         FlightNo = string.Format(@"{0}{1}",l.Airline,l.FltNo)
                }.Save();
            });
            PnrInfoResult.PassengerList.ToList().ForEach(l => {
                new PnrPassenger()
                {
                 IdentityNo = l.DocumentNo,
                  IdentityType = string.IsNullOrEmpty(l.DocumentType)?(int)PNRPassengerIdentityType.身份证:(int)PNRPassengerIdentityType.其它,
                   PassengerName = l.FullName,
                    PassengerType = l.AgeType==@"AD"?(int)PNRPassengerType.AD:(l.AgeType==@"CH"?(int)PNRPassengerType.CH:(int)PNRPassengerType.IN),
                     RequireId = model.Id,
                      Birthday =null,
                }.Save();
            });
        }

        protected DateTime? getDateString(string date)
        {
            Match m = Regex.Match(date, @"(\d+)([A-Z]{3})(\d{0,2})", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if (!m.Success) return null;
            int month = new List<string>() { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }.IndexOf(m.Groups[2].Value.ToLower()) + 1;
            return new DateTime(DateTime.Now.Year, month, int.Parse(m.Groups[1].Value));
        }




        protected override PnrRequire GetEntityFromControl()
        {
            return new PnrRequire() {
                Description = tbDescription.Text.Trim(),
                 PnrCode = tbPNRCode.Text.Trim(),
                  RecordDate = DateTime.Now,
                   UserId = UID,
                    RequireCode = StringUtil.GenUniqueString(),
                StatusId = (int)PNRRequireStatus.PENDDING
            };
        }
    }
}